package com.yejiarong.influxdb.common.interceptor;

import com.yejiarong.common.enums.RequestHeaderKeyEnums;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

/**
 * @author YeJR
 */
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    private static final String START_TIME = "startTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute(START_TIME, System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        long startTime = (Long) request.getAttribute(START_TIME);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        String port = Optional.ofNullable(request.getHeader(RequestHeaderKeyEnums.SERVER_PORT.name())).orElse("-");
        String ipAddress = Optional.ofNullable(request.getHeader(RequestHeaderKeyEnums.SERVICE_HOST.name())).orElse("-");
        String serviceName = Optional.ofNullable(request.getHeader(RequestHeaderKeyEnums.SERVICE_NAME.name())).orElse("-");
        log.info("ClientName: {}, ClientIp: {}, ClientPort:{}, Path: {} {} | Time taken: {}ms", serviceName, ipAddress, port, request.getMethod(), request.getRequestURI(), duration);
    }
}
